package com.ws.webpacket.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.sdk.WebView;
import com.ws.webpacket.R;
import com.ws.webpacket.activity.dialog.UpDataDialog;
import com.ws.webpacket.activity.dialog.UrlSelectDialog;
import com.ws.webpacket.internet.HttpAPI;
import com.ws.webpacket.internet.been.B_Ping;
import com.ws.webpacket.internet.been.B_RootList;
import com.ws.webpacket.util.HLog;
import com.ws.webpacket.util.SharedPerformanceUtile;
import com.ws.webpacket.util.SpUtils;
import com.ws.webpacket.util.VersionManager;
import com.ws.webpacket.view.FloatButton;
import com.ws.webpacket.view.LoadingView;
import com.ws.webpacket.view.WebClientOption;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    public static FrameLayout getWebLayout() {
        return webLayout;
    }

//=========================================================================================
//  View
//=========================================================================================

    private static FrameLayout webLayout;
    private FloatButton floatButton;

    private LoadingView loadingView;
    private TextView loadingTips;
    private LinearLayout loadingLayout;

    private UrlSelectDialog selectDialog;
    private ViewGroup activityRoot;

    private boolean isRefreshing = false;

    private List<WebClientOption> webClientOptions = new ArrayList<>();
    public static WebClientOption actionWebOption;

    public static boolean avtivityCreated = false;
    public static String adUrl = null;  // 推送广播地址

    private void initView() {
        floatButton = findViewById(R.id.floatButton_MainActivity_Option);
        floatButton.setOnClickListener(onClickListener);

        activityRoot = findViewById(R.id.constraintLayout_MainActivity_Root);
//      activityRoot.setOnClickListener(onClickListener);

        loadingView = findViewById(R.id.loadingView_MainActivity);
        loadingLayout = findViewById(R.id.loadinglayout);
        loadingTips = findViewById(R.id.textView_MainActivity_tips);

        webLayout = findViewById(R.id.frameLayout_Main_WebLayout);
        actionWebOption = new WebClientOption(this);
        webLayout.addView(actionWebOption.getWebView());
        actionWebOption.setWebViewLoadingListener(webViewLoadingListener);
        actionWebOption.setActionListener(actionListener);
        actionWebOption.setActivity(this);

    }

    private void loadUrl(B_Ping url) {

        if (loadUrl == url) return;
        for (int i = 0; pings != null && i < pings.size(); i++) {
            pings.get(i).setLoade(false);
        }

        loadUrl = url;
        url.setLoade(true);

        loadingView.setVisibility(View.VISIBLE);
        loadingView.loding();
        loadingTips.setVisibility(View.VISIBLE);

        HLog.I("加载网络地址：" + url.getUrl() + "/m/#/home/?android=true");

        actionWebOption.loadUrl(url.getUrl() + "/m/#/home/?android=true");//加载外网
    }

    private void loadingView(boolean load) {
        if (load) {
            loadingView.setVisibility(View.VISIBLE);
            loadingTips.setVisibility(View.VISIBLE);
            loadingLayout.setVisibility(View.VISIBLE);
            loadingView.loding();
        } else {
            loadingView.setVisibility(View.GONE);
            loadingTips.setVisibility(View.GONE);
            loadingLayout.setVisibility(View.GONE);
            loadingView.stopLode();
        }
    }

//=========================================================================================
//  Control
//=========================================================================================

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String str = SpUtils.getString(MainActivity.this, "FirstOpen");
        if (TextUtils.isEmpty(str)) {
            Toast.makeText(this, "首次加载组件可能时间较久，请耐心等待", Toast.LENGTH_LONG).show();
            SpUtils.putString(MainActivity.this, "FirstOpen", "1");
        }
        
        initView();
        initInfo();
        avtivityCreated = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        avtivityCreated = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webClientOptions.size() != 0) {
                WebView webView = actionWebOption.getWebView();
                webView.onPause();
                webView.destroy();
                webLayout.removeView(webView);

                actionWebOption = webClientOptions.get(0);
                webClientOptions.remove(0);
                webView = actionWebOption.getWebView();
                webLayout.addView(webView);
                webView.onResume();
                return true;
            } else if (actionWebOption.goBack()) {
                return true;
            } else {
                if (startBackClick == 0) {
                    //  当前页面是广告页，当广告页退出后加载平台主页
                    if (adUrl != null) {
                        adUrl = null;
                        urlLoaded = false;
                        loatBaseUrl();
                    } else { // 如果当前页面已经是平台主页则开始处理关闭流程
                        startBackClick = System.currentTimeMillis();
                        Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    }
                } else if (DOUBLE_CLICK > (System.currentTimeMillis() - startBackClick)) {
                    System.exit(0);
                } else {
                    startBackClick = 0;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WebClientOption.FILECHOOSER_RESULTCODE || requestCode == WebClientOption.FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            actionWebOption.onActivityResult(requestCode, resultCode, data);
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.floatButton_MainActivity_Option:
                    if (selectDialog == null) {
                        selectDialog = new UrlSelectDialog();
                        selectDialog.setUrlSelectAction(urlSelectAction);
                        selectDialog.refreshUrlList(pings);
                    }
                    selectDialog.show(getSupportFragmentManager(), "selectUrl");
                    break;
            }
        }
    };

    private WebClientOption.WebViewLoadingListener webViewLoadingListener = new WebClientOption.WebViewLoadingListener() {

        @Override
        public void loading(int newProgress, String url) {
            loadingView(true);
            loadingTips.setText(newProgress + "%");
        }

        @Override
        public void loadEnd(String msg) {
            loadingView(false);
        }

        @Override
        public void error(int code, String msg) {
            loadingView(false);
        }

    };

    private WebClientOption.ActionListener actionListener = new WebClientOption.ActionListener() {

        @Override
        public void newWiondow(WebClientOption webClientOption) {
            webClientOption.setWebViewLoadingListener(webViewLoadingListener);
            webClientOption.setActionListener(actionListener);
            webClientOption.setActivity(MainActivity.this);

            WebView webView = webClientOption.getWebView();
            webLayout.addView(webView);
            webView.onResume();

            webView = actionWebOption.getWebView();
            webView.onPause();
            webLayout.removeView(webView);
            webClientOptions.add(actionWebOption);

            actionWebOption = webClientOption;
        }
    };

    private HttpAPI.GetRootUrl getRootUrl = new HttpAPI.GetRootUrl() {
        @Override
        public void result(final B_RootList result) {

            rootList = result;
            final VersionManager versionManager = new VersionManager();
            if (versionManager.versionCheck(MainActivity.this, 0, result.getVerson()) &&
                    !SharedPerformanceUtile.get(MainActivity.this, SharedPerformanceUtile.SAVE_STATUS)) {
                UpDataDialog dataDialog = new UpDataDialog(result);
                dataDialog.show(getSupportFragmentManager(), "upDataDialog");
                dataDialog.setDownLoadListener(new UpDataDialog.DownLoadListener() {
                    @Override
                    public void startDownLoad() {
                        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setCancelable(false);
                        progressDialog.setTitle("新版本");
                        progressDialog.setMessage("正在下载新版本...");
                        progressDialog.setMax(100);

                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.show();

//                        String url = "https://xtyb5app.ws88168.com/apps/b5-1.1.2.apk?1574847811184";
//                        versionManager.downLoadAPP(MainActivity.this,url);
                        versionManager.downLoadAPP(MainActivity.this, rootList.getDef().get(0));
//                        SYSOUtils.sOut_("+++++++++解析到的1+++++++++++"+rootList.getDef().get(0));
                        versionManager.setDownLoadListener(new VersionManager.DownLoadListener() {
                            @Override
                            public void progress(float progress) {
                                HLog.I("下载进度 " + progress);
                                progressDialog.setProgress((int) progress);
                            }

                            @Override
                            public void finish(String dir) {
                                HLog.I("开始下载内容 " + dir);
                                progressDialog.dismiss();
                                VersionManager.installAPK(MainActivity.this, dir);
                            }
                        });
                    }
                });
            }
            if (!urlLoaded)
                loadingTips.setText("优化访问速度...");

            pintUrl();
        }

        @Override
        public void error(String msg) {
            loadingTips.setText("网络请求失败，点击刷新页面。");
        }

    };

    private HttpAPI.PingRequest pingRequest = new HttpAPI.PingRequest() {
        @Override
        public void result(B_Ping result) {
            pingsCache.add(result);
            if (loadUrl != null && result.getIndex() == loadUrl.getIndex()) {
                result.setLoade(true);
            }
            pintUrl();
        }

        @Override
        public void error(String msg) {

            pings.add(null);
            pintUrl();
        }
    };

    private UrlSelectDialog.UrlSelectAction urlSelectAction = new UrlSelectDialog.UrlSelectAction() {
        @Override
        public void selected(B_Ping url) {
            loadUrl(url);
            selectDialog.dismiss();
        }

        @Override
        public void rePingUrl() {
            //  避免重复
            if (isRefreshing) {
                return;
            }
            pingIndex = 0;
            pintUrl();
        }

        @Override
        public void loadHome() {
            WebView webView = actionWebOption.getWebView();
            if (webClientOptions.size() > 0) {
                webLayout.removeView(actionWebOption.getWebView());

                actionWebOption = webClientOptions.get(webClientOptions.size() - 1);
                webView = actionWebOption.getWebView();
                webView.onResume();
                webLayout.addView(webView);

                webClientOptions.clear();
            }

            while (webView.canGoBack()) {
                webView.goBack();
            }
        }

        @Override
        public void floatWindow() {
            if (serverStarted) {
                Intent intent = new Intent();
                intent.setAction(BC_SHOWFLOATING);
                localBroadcastManager.sendBroadcast(intent);

                activityRoot.removeView(webLayout);

                finish();
            } else {
                Toast.makeText(MainActivity.this, "服务还未启动请稍后", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, GameFloatView.class);
                startService(intent);
            }
        }
    };

    private BroadcastReceiver activityBroadCast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case GameFloatView.BC_SERVER_STARTED:
                    serverStarted = true;
                    break;
            }
        }
    };


//=========================================================================================
//  Model
//=========================================================================================

    private B_RootList rootList;
    private int pingIndex = 0;
    private List<B_Ping> pings;
    private List<B_Ping> pingsCache;
    private B_Ping loadUrl;
    private boolean urlLoaded = false;

    private long startBackClick = 0;
    private static final int DOUBLE_CLICK = 800;//双击的点击时间间隔

    private boolean serverStarted = false;
    private LocalBroadcastManager localBroadcastManager;

    public static final String BC_SHOWFLOATING = "com.ws.webpacket.activity.showFloating";

    private void initInfo() {
        loadingTips.setText("地址获取中...");
        HLog.I("initInfo  地址获取中 ");
        // 如果是点击广告进入则只加载广告地址
        if (adUrl != null) {
            urlLoaded = true;
            actionWebOption.loadUrl(adUrl);//加载外网
        }

        // 如果已经加载过网络地址，默认使用上一次URL列表，用于优化访问速度
        pings = SharedPerformanceUtile.getLoadUrl(this);
        loatBaseUrl();

        pings = new ArrayList<>();
        pingsCache = new ArrayList<>();
        getRootUrl.startRequest();

        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(GameFloatView.BC_SERVER_STARTED);
        localBroadcastManager.registerReceiver(activityBroadCast, intentFilter);

        Intent intent = new Intent(this, GameFloatView.class);
        startService(intent);
    }

    private void pintUrl() {

//        HLog.I("重新pingUrl");

        if (pingIndex == 0) {
            isRefreshing = true;
            pingsCache.clear();
        }

        if (pingIndex < rootList.getHosts().size()) {
//            HLog.I("链接网络  "+rootList.getHosts().get(pingIndex));
            pingRequest.startRequest(rootList.getHosts().get(pingIndex), pingIndex);

            pingIndex++;
        } else {
            isRefreshing = false;

            pings.clear();
            pings.addAll(pingsCache);

            if (selectDialog != null) {
                selectDialog.refreshUrlList(pings);
            }

            //检测 如果所有线路都无法使用则显示提示
            B_Ping ping = null;
            for (int i = 0; i < pings.size(); i++) {
                if (pings.get(i) != null) {
                    ping = pings.get(i);
                }
            }
            if (ping != null) {
                SharedPerformanceUtile.putLoadUrl(this, pings);
                loatBaseUrl();
            } else {
                Toast.makeText(this, "线路加载失败", Toast.LENGTH_SHORT).show();
                loadingTips.setText("线路加载失败");
            }
        }
    }

    private void loatBaseUrl() {
        if (urlLoaded) return;
        B_Ping ping = null;
        for (int i = 0; i < pings.size(); i++) {
            if (ping == null || ping.getOverTime() > pings.get(i).getOverTime()) {
                ping = pings.get(i);
                urlLoaded = true;
            }
        }
//      HLog.I("initInfo  地址获取后 "+ pings.size());
        loadUrl(ping);
    }

}
